from fastapi import APIRouter, Request, Form, Depends, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from database import get_db
from models import Users, ApiCalls, ApiCallLogs, UserType
from datetime import datetime, date
import random

router = APIRouter(tags=["视频解析模块"], prefix="/video")

LIMITS = {"free":10, "month":2000, "season":3500, "year":8000}


def verify_client(client_id: str, client_secret: str, db: Session):
    user = db.query(Users).filter_by(client_id=client_id, client_secret=client_secret).first()
    if not user or user.status != 1:
        raise HTTPException(401, "无效的接口凭证")
    limit = LIMITS.get(user.user_type.value, 10)
    today = date.today()
    record = db.query(ApiCalls).filter_by(user_id=user.user_id, call_date=today).first()
    if not record:
        record = ApiCalls(user_id=user.user_id, call_date=today, call_count=0)
        db.add(record)
    if record.call_count >= limit:
        raise HTTPException(403, "调用次数已达上限")
    record.call_count += 1
    log = ApiCallLogs(user_id=user.user_id, url="测试视频链接")
    db.add(log)
    db.commit()
    return user


@router.get("/parse")
def parse_video(url: str, client_id: str, client_secret: str, db: Session = Depends(get_db)):
    user = verify_client(client_id, client_secret, db)
    return {"user": user.username, "url": url, "result": f"https://cdn.fake/{random.randint(1000,9999)}.mp4"}


# 模拟解析函数
def parse_video_or_images(url: str) -> dict:
    import json
    import asyncio
    from parser import parse_video_share_url, parse_video_id, VideoSource

    # 根据分享链接解析
    video_parse_info = asyncio.run(parse_video_share_url(url))
    print(
        "解析分享链接：\n",
        json.dumps(video_parse_info, ensure_ascii=False, indent=4, default=lambda x: x.__dict__),
        "\n",
    )
    print(type(video_parse_info), video_parse_info)

    json_str_video_info = json.dumps(video_parse_info, ensure_ascii=False, indent=4, default=lambda x: x.__dict__)
    print(type(json_str_video_info), json_str_video_info)

    json_obj = json.loads(json_str_video_info)

    # if video_parse_info:
    #     if video_parse_info["video_url"]:
    #         print("视频")
    #     else:
    #         print("图文")
    #
    #     print(video_parse_info)
    #
    #     return {"cover": "https://via.placeholder.com/400", "url": "", "pics": [
    #         "https://via.placeholder.com/200",
    #         "https://via.placeholder.com/201",
    #         "https://via.placeholder.com/202"
    #     ]}


    if "image" in url:
        return {"cover": "https://via.placeholder.com/400", "url": "", "pics": [
            "https://via.placeholder.com/200",
            "https://via.placeholder.com/201",
            "https://via.placeholder.com/202"
        ]}
    else:
        return {"cover": "https://via.placeholder.com/400", "url": "https://www.w3schools.com/html/mov_bbb.mp4", "pics": None}


# 视频/图集解析接口
@router.post("/jiexi")
def jiexi(url: str = Form(...), request: Request = None, db: Session = Depends(get_db)):
    user_id = request.session.get("user_id")
    print("user_id = ", user_id)
    if user_id:
        user = db.query(Users).filter(Users.user_id == user_id).first()
        client_id = user.client_id
        client_secret = user.client_secret
        if not client_secret:
            return JSONResponse({"code": 107, "msg": "请先开通接口权限"})

        if user.user_type.value != 'admin':
            limit = 100000
        else:
            # 获取用户分类，如果没有找到分类，默认返回10
            limit = LIMITS.get(user.user_type.value, 10)
        today = date.today()
        record = db.query(ApiCalls).filter_by(user_id=user.user_id, call_date=today).first()
        if not record:
            record = ApiCalls(user_id=user.user_id, call_date=today, call_count=0)
            db.add(record)
        if record.call_count >= limit:
            return JSONResponse({"code": 108, "msg": "调用次数已达上限"})

        try:
            data = parse_video_or_images(url)
            # 增加1次接口调用次数
            record.call_count += 1
            log = ApiCallLogs(user_id=user.user_id, url=url)
            db.add(log)
            db.commit()
            return JSONResponse({"code": 200, "msg": "解析成功", "data": data})

        except Exception as e:
            return JSONResponse({"code": 500, "msg": f"解析失败: {str(e)}"})
    else:
        return JSONResponse({"code": 106, "msg": "请登录后使用"})









